<!--
 * @Description: 职位管理-添加组织
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-29
-->
<template>
  <div class="add">
    <a-modal v-model:visible="visible" title="添加组织" @ok="form.onOk">
      <a-form-item label="组织名称" v-bind="validateInfos.name">
        <a-input v-model:value="form.state.name" />
      </a-form-item>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, watch } from 'vue'

  import { requestSaveDept } from '/@/api/business/company/dept'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getCompanyInfo } from '/@/storage'

  const { companyId } = getCompanyInfo()

  const props = defineProps({
    visible: { type: Boolean, default: false },
    parentDeptId: { type: Number, default: NaN },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) resetFields()
    },
  )

  /** 表单配置 */
  const form = reactive({
    state: {
      name: '',
    },
    rule: {
      name: [{ required: true, message: '请输入组织名称' }],
    },
    onOk: () => {
      validate()
        .then(async () => {
          const { responseCode } = await requestSaveDept({ companyId, deptName: form.state.name, parentId: props.parentDeptId })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            message.success('添加成功')
            visible.value = false
            emits('success')
          }
        })
        .catch(() => {})
    },
  })
  /** 表单hook */
  const { validate, validateInfos, resetFields } = Form.useForm(form.state, form.rule)
</script>

<style lang="less" scoped></style>
